package com.fsoft.core.context;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 用于保存spring的applicationContext 注意这里不是springMVC的哦
 * 
 * @author gk @date 2017-4-9 下午2:10:00
 */
public class ApplicationContextHolder implements ApplicationContextAware {

	private static Logger log = LoggerFactory.getLogger(ApplicationContextHolder.class);
	private static ApplicationContext applicationContext;

	@Override
	@SuppressWarnings("all")
	public void setApplicationContext(ApplicationContext context) throws BeansException {
		if (context != null && !context.equals(this.applicationContext)) {
			this.applicationContext = context;
			log.info("获取Spring 上下文:" + applicationContext.getDisplayName());
		}
	}

	public static ApplicationContext getApplicationContext() {
		if (applicationContext == null) {
			throw new IllegalStateException("无法获取系统上下文");
		}
		return applicationContext;
	}

	public static Object getBean(String beanName) {
		return getApplicationContext().getBean(beanName);
	}

	public static void cleanHolder() {
		applicationContext = null;
	}

}
